<?php

namespace app\api\model;

use app\common\enums\StatusEnum;
use app\api\model\LangClassVideoTransfer AS LangClassVideoTransferModel;
use think\Db;

class LangClassFile extends \app\common\model\LangClassFile
{
    /**
     * 首页搜索，根据视频名称
     * @param $name
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function search($name)
    {
        return static::field('l.id AS langId, l.icon, l.name')
            ->alias('f')
            ->join('lang_class c', 'f.class_id = c.id', 'INNER')
            ->join('lang l', 'l.id = c.lang_id', 'INNER')
            ->where('f.file_name', 'like', '%' . $name . '%')
            ->where([
                'f.type' => self::TYPE_VIDEO,
                'f.status' => StatusEnum::ENABLED,
                'c.status' => StatusEnum::ENABLED,
                'l.status' => StatusEnum::ENABLED
            ])->select()->toArray();
    }

    /**
     * 免费视频列表
     * @param int $page 第几页
     * @param int $size 每页条数
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function freeList($page, $size)
    {
        $offset = ($page - 1) * $size;
        $where = [
            'f.status' => StatusEnum::ENABLED,
            'f.type' => self::TYPE_VIDEO,
            'f.is_free' => self::FREE,
            'c.status' => StatusEnum::ENABLED,
            'l.status' => StatusEnum::ENABLED
        ];

        $sql = static::field('f.id as fileId, f.class_id AS classId, f.course_type AS courseType, f.file, f.file_name AS fileName, f.video_img AS videoImg,l.id AS langId')
            ->alias('f')
            ->join('lang_class c', 'f.class_id = c.id', 'INNER')
            ->join('lang l', 'l.id = c.lang_id', 'INNER')
            ->where($where);

        $model = $sql->order(['f.sort_num' => 'desc', 'f.create_time' => 'desc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();

        foreach ($model as $key => $value) {
            $model[$key]['file'] = config('file_prefix') . $value['file'];
            $model[$key]['videoImg'] = $value['videoImg'] ? config('file_prefix') . $value['videoImg'] : '';
        }
        return [
            'list' => $model,
            'count' => $sql->count(),
        ];
    }

    /**
     * 通过班级id和课程类型，课件类型获取对应的文件列表
     * @param int $classId 班级id
     * @param int $courseType 课程类型，1语音课，2基础课，3高级课
     * @param int $type 文件类型，视频1，音频2，学习资料课件下载3，学习资料随堂作业4
     * @param int $page 页数
     * @param int $size 每页条数
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function getList($classId, $courseType, $type, $page, $size)
    {
        $offset = ($page - 1) * $size;

        $sql = static::where([
            'class_id' => $classId,
            'course_type' => $courseType,
            'type' => $type,
            'status' => StatusEnum::ENABLED
        ]);

        // 不返回文件路径，点击的时候再请求判断是否已经购买
        $model = $sql->field('class_id AS classId, course_type AS courseType, id AS fileId, file, file_name AS fileName, video_img AS videoImg, is_free AS isFree, create_time AS createTime')
            ->order(['sort_num' => 'desc', 'create_time' => 'asc'])
            ->limit($offset, $size)
            ->select()
            ->toArray();
        foreach ($model as $key => $value) {
            $model[$key]['videoImg'] = $value['videoImg'] ? config('file_prefix') . $value['videoImg'] : '';
            $model[$key]['createTime'] = date('Y-m-d', $value['createTime']);
            $model[$key]['isDownload'] = self::fileIsDownload($value['fileId']);
            $model[$key]['icon'] = self::langIcon($value['classId']);
        }

        // 通过班级ID查找语种
        $title = '';
        $class = LangClass::getClass($classId);
        if ($class) {
            $title = $class['langName'] . LangClass::attributes('type', $class['type']);
        }

        foreach ($model as $key => $value) {
            
            // 课件、随堂作业需要预览，返回文件路径和后缀
            $model[$key]['file'] = config('file_prefix') . $value['file'];
            $model[$key]['fileSuffix'] = substr(strrchr($value['file'], '.'), 1);
            
        }

        return [
            'title' => $title,
            'list' => $model,
            'count' => $sql->count(),
        ];
    }

    /**
     * 判断指定文件是否能看
     * @param $oauthId
     * @param $fileId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function canWatch($oauthId, $fileId)
    {
        // 查找文件对应的班级
        $file = static::field('id AS fileId, file, file_name AS fileName, class_id AS classId, 
        type, is_free AS isFree, description,video_img')
            ->where(['id' => $fileId, 'status' => StatusEnum::ENABLED])
            ->find();
        if (empty($file)) {
            return [];
        }

        $canWatch = false;
        // 免费视频可以观看
        if ($file['isFree'] == self::FREE) {
            $canWatch = true;
        } else {
            // 非免费，判断是否已经购买
            $buyLog = OauthOrderClass::getOneByClass($oauthId, $file['classId']);
            if ($buyLog) {
                // 已经购买可以观看
                $canWatch = true;
                // 视频、音频、课件添加或者更新我的轨迹记录
                if (in_array($file['type'], self::WATCH_LOG_ARR)) {
                    OauthWatchLog::addOne($oauthId, $fileId);
                }
            }
        }

        return [
            'classId' => $file['classId'],
            'fileId' => $file['fileId'],
            'file' => config('file_prefix') . $file['file'],
            'fileName' => $file['fileName'],
            'fileType' => $file['type'],
            'description' => $file['description'],
            'canWatch' => $canWatch,
            'videoImg' => config('file_prefix') .$file['video_img']
        ];
    }
    

    /**
     * 判断指定转码文件是否能看
     * @param $oauthId
     * @param $fileId
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function canTransferWatch($oauthId, $fileId,$type)
    {
        // 查找文件对应的班级
        $file = static::field('id AS fileId, file, file_name AS fileName, class_id AS classId, 
        type, is_free AS isFree, description,video_img')
            ->where(['id' => $fileId, 'status' => StatusEnum::ENABLED])
            ->find();
        if (empty($file)) {
            return [];
        }

        $canWatch = false;
        // 免费视频可以观看
        if ($file['isFree'] == self::FREE) {
            $canWatch = true;
        } else {
            // 非免费，判断是否已经购买
            $buyLog = OauthOrderClass::getOneByClass($oauthId, $file['classId']);
            if ($buyLog) {
                // 已经购买可以观看
                $canWatch = true;
                // 视频、音频、课件添加或者更新我的轨迹记录
                if (in_array($file['type'], self::WATCH_LOG_ARR)) {
                    OauthWatchLog::addOne($oauthId, $fileId);
                }
            }
        }
        $record = LangClassVideoTransferModel::getRecordByFile($file['file'],$type);
        
        if(empty($record) || $record['status'] != 1){
            return [];
        }
        return [
            'classId' => $file['classId'],
            'fileId' => $file['fileId'],
            'file' => config('file_prefix') . $record['transterFile'],
            'fileName' => $file['fileName'],
            'fileType' => $file['type'],
            'description' => $file['description'],
            'canWatch' => $canWatch,
            'videoImg' => config('file_prefix') .$file['video_img']
        ];
    }
    
    
    public static function fileIsDownload($fileId)
    {
        // 查找文件对应的班级
        $file = DB::table('cache_list')->field('cache_id')
            ->where(['class_file_id' => $fileId])
            ->find();
       return $file['cache_id']?1:0;
    }
    
    
    public static function langIcon($classId)
    {
        // 查找文件对应的班级
        $langInfo = DB::table('lang_class')->field('f.lang_id, l.icon')
            ->alias('f')
            ->join('lang l', 'l.id = f.lang_id')
            ->where(['f.id' => $classId])
            ->find();
        return config('file_prefix').$langInfo['icon'];
    }
}